package com.learn.config;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.function.Predicate;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/08/05
 * @description ch09 网关
 * 自定义路由断言类
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        // 可以用lambda
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                return userType != null && userType.equalsIgnoreCase(config.getUserType());
            }
        };
    }

    /**
     * 配置短模式，这里表明可以按yaml的list格式写
     * @return
     */
    public List<String> shortcutFieldOrder() {
        return List.of("userType");
    }

    /**
     * 断言规则
     */
    @Validated
    public static class Config {
        @NotEmpty
        private String userType;

        public Config() {
        }

        public String getUserType() {
            return userType;
        }

        public void setUserType(String userType) {
            this.userType = userType;
        }
    }
}
